#include "tenantsmodel.h"
#include <QDebug>

TenantsModel::TenantsModel(QObject *parent) :
    QAbstractTableModel(parent)
{
}

void TenantsModel::load_data()
{
    mqvl_indexes.clear();
    mqhl_data.clear();
    mqvl_indexes = mp_dbms->get_db(LAKDB_TENANTS)->findDataRange(FLD_TEN_FAM, NULL, true, NULL, false, &mqhl_data);
    mqvl_indexes.removeFirst();
    mqhl_data.removeFirst();
    qDebug()<<"tenants model. data loaded. size:"<<mqvl_indexes.size();
}


int TenantsModel::rowCount(const QModelIndex &/*parent*/) const
{
    return mqvl_indexes.size();
}

int TenantsModel::columnCount(const QModelIndex &/*parent*/) const
{
    return 6;
}

QVariant TenantsModel::data(const QModelIndex &index, int role) const
{
    if(role != Qt::DisplayRole) return QVariant();
    int r = index.row();
    int c = index.column();
    QString qstr;
    switch(c)
    {
    case 0: qstr = mp_dbms->get_tenant_fio(mqhl_data.at(r)); break;
    case 1:  qstr = mp_dbms->get_tenant_dob_str(mqhl_data.at(r)); break;
    case 2: qstr = mqhl_data.at(r).value(FLD_TEN_PASSNUM).toString(); break;
    case 3: qstr = mqhl_data.at(r).value(FLD_TEN_PASSDATE).toDate().toString("dd.MM.yy") + "\n";
                  qstr += mqhl_data.at(r).value(FLD_TEN_PASSDEP).toString(); break;
    case 4: qstr += mqhl_data.at(r).value(FLD_TEN_REGADR).toString(); break;
    case 5: qstr += mqhl_data.at(r).value(FLD_TEN_COMM).toString();
    }
    return QVariant(qstr);
}

QVariant TenantsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if(role != Qt::DisplayRole) return QVariant();
    if(orientation == Qt::Vertical) return QVariant();
    QString qstr;
    switch(section)
    {
    case 0: qstr = RUSTR("Фамилия И.О."); break;
    case 1: qstr = RUSTR("Дата рожд."); break;
    case 2: qstr = RUSTR("Паспорт"); break;
    case 3: qstr = RUSTR("Выдан"); break;
    case 4: qstr = RUSTR("Адрес регистрации"); break;
    case 5: qstr = RUSTR("Коментарии"); break;
    }
    return QVariant (qstr);
}


QVariant TenantsModel::get_db_index(const QModelIndex &index)
{
    if(!index.isValid()) return QVariant();
    return mqvl_indexes.at(index.row());
}

QModelIndex TenantsModel::get_model_index(const QVariant &qv_index)
{
    int r = mqvl_indexes.indexOf(qv_index);
    if(r < 0) return QModelIndex();
    return createIndex(r, 0);
}

SLEE_HDB_REC TenantsModel::get_data(const QVariant &qv_index)
{
    int r = mqvl_indexes.indexOf(qv_index);
    if(r <0) return SLEE_HDB_REC();
    return mqhl_data.at(r);
}

void TenantsModel::update_data(const QVariant &qv_index)
{
    int r = mqvl_indexes.indexOf(qv_index);
    if(r < 0) return;
    mqhl_data[r] = mp_dbms->get_data(LAKDB_TENANTS,qv_index);
}
